package org.uni_hi.muus.bluetooth;

import java.io.IOException;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.StreamConnection;

import org.uni_hi.muus.server.RequestHandler;
import org.uni_hi.muus.server.Server;
import org.uni_hi.muus.server.util.HTTPServerCodes;

public class BluetoothServer extends Server {

	protected static final UUID MuuS_SERVICE_UUID=new UUID("dd972210026711de87af0800200c9a66",false),SPP_SERVICE_ID=new UUID("1101",true);
	protected static final int DISCOVERY_ATTRIBUTE=0x4321;
	protected static final int[] ATTRIBUTE_SET={DISCOVERY_ATTRIBUTE};
	protected static final UUID[] UUID_SET={SPP_SERVICE_ID,MuuS_SERVICE_UUID};
	private static StringBuffer _btURL;
	private LocalDevice _localDevice=null;

	/**
	 * Starts the Bluetooth interface and 
	 * initializes all required values 
	 * @throws IOException 
	 */
	public BluetoothServer() throws IOException{
		super(getBluetoothURL());
		try {
			initBluetoothServer();
		} catch (BluetoothStateException e) {
			// TODO Post a message that Bluetooth is not available for this server!
			e.printStackTrace();
		} catch (IOException e){
			// TODO Post a message that Bluetooth Server is not visible!
			e.printStackTrace();
		}
	}

	private void initBluetoothServer() throws BluetoothStateException, IOException{
		//our own device
		_localDevice=LocalDevice.getLocalDevice(); 
		//sets the device visible for unlimited time - for only few minutes use DiscoveryAgent.LIAC
		if(!_localDevice.setDiscoverable(DiscoveryAgent.GIAC)){
			throw new IOException("Not able to set the device always visible.");
		}
		
	}

	private static String getBluetoothURL(){
		if(_btURL==null){
			_btURL=new StringBuffer("btspp://localhost:");
			_btURL.append(MuuS_SERVICE_UUID);
			_btURL.append(";name="+HTTPServerCodes.HTTP_SERVER_NAME);
			_btURL.append(";authorize=false");
		}
		return _btURL.toString();
	}

	protected void openAndAccept() throws IOException {
		StreamConnection sc = (StreamConnection)_scn.acceptAndOpen();
		// service the connection in a separate thread
		RequestHandler rh = new RequestHandler(sc);
	}
}
